<?php
declare(strict_types=1);

namespace SixShop\System\Cron;

use SixShop\Core\Attribute\Cron;
use think\Cache;
use Workerman\Crontab\Crontab;
use Workerman\Worker;

class SystemCron
{
    public function __construct(private Cache $cache, private bool $isStart = false)
    {
    }

    #[Cron('1 * * * * *', 'system.cron')]
    public function onWorkerStart(): void
    {
        $crontabList = [];
        foreach (Crontab::getAll() as $item) {
            /* @var Crontab $item */
            $item = [
                'rule' => $item->getRule(),
                'name' => $item->getName(),
                'id' => $item->getId(),
                'time' => date('Y-m-d H:i:s'),
            ];
            $crontabList[] = $item;
            if (!$this->isStart) {
                Worker::safeEcho(sprintf('[%s] [%s] [%s] [%s]', $item['time'], $item['id'], $item['name'], $item['rule']) . "\n");
            }
        }
        $this->cache->set('crontab_list', $crontabList);
        $this->isStart = true;
    }

    #[Cron('1 0 0 * * *', 'system.cron.change_log_file')]
    public function changeLogFile(): void
    {
        Worker::$logFile = root_path('runtime/log')  . date('Ymd') . '_crontab.log';
    }
}